package com.hx.zhg.util;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.File;
import java.io.InputStream;

public class FileUtilExt {

    private static final Logger log = LoggerFactory.getLogger(FileUtilExt.class);

    public static boolean delete(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            return file.delete();
        }
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isFile()) {
                if (!f.delete()) {
                    System.out.println(f.getAbsolutePath() + " delete error!");
                    return false;
                }
            } else {
                if (!delete(f.getAbsolutePath())) {
                    return false;
                }
            }
        }
        return file.delete();
    }

    /**
     * 将jar包中的目录拷贝到外部，可供其他使用
     *
     * @param path
     */
    public static void loadCopyResources(String path) {
        String outPath = path.substring(0, path.lastIndexOf("*"));
        String targetDir = SystemPropertiesUtil.getUserDir() + File.separator + outPath;
        //删除重新拷贝
        delete(targetDir);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //获取所有匹配的文件
            Resource[] resources = resolver.getResources(path);
            for (Resource resource : resources) {
                //获得文件流，因为在jar文件中，不能直接通过文件资源路径拿到文件，但是可以在jar包中拿到文件流
                InputStream stream = resource.getInputStream();
                if (log.isInfoEnabled()) {
                    log.info("读取的文件流  [" + stream + "]");
                }
                String targetFilePath = targetDir + resource.getFilename();
                if (log.isInfoEnabled()) {
                    log.info("放置位置  [" + targetFilePath + "]");
                }

                File outLibDir = new File(targetDir);
                if (!outLibDir.exists()) {
                    outLibDir.mkdirs();// 能创建多级目录
                }

                File ttfFile = new File(targetFilePath);
                FileUtils.copyInputStreamToFile(stream, ttfFile);
            }
        } catch (Exception e) {
            if (log.isWarnEnabled()) {
                log.warn("读取文件流失败，写入本地库失败！ " + e);
            }
        }
    }
}
